package cn.loioi.web.controller.admin.user;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;

import cn.loioi.multi.mysql.model.SysUser;
import cn.loioi.multi.service.user.SysUserService;
import cn.loioi.util.RequestUtil;
import cn.loioi.web.common.BaseJqGridController;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :账户管理 <br>
 * @file_name :AccountContorller.java <br>
 * @system_name :multi_project_web <br>
 * @author :yyzh <br>
 * @创建时间 :2016年7月26日 下午1:43:16
 */
@Controller
@RequestMapping("/admin/user/account")
public class AccountContorller extends BaseJqGridController<SysUser, SysUserService> {

	@Autowired
	public AccountContorller(SysUserService service) {
		super("admin/user/account/", "user:account", service);
	}

	@Override
	protected Model editHandle(HttpServletRequest request, Model model, SysUser record) {
		if (baseService.updateByAccount(record) > 0) {
			return renderSuccess(model, "更新成功");
		} else {
			return renderFail(model, "更新失败");
		}
	}

	/**
	 * 修改密码
	 * @param request
	 * @param model
	 * @return
	 */
	@RequiresRoles("manage")
	@RequestMapping("password.json")
	public Model password(HttpServletRequest request, Model model) {
		String account = RequestUtil.getValueStr(request, "account");
		String password = RequestUtil.getValueStr(request, "password");
		String password_again = RequestUtil.getValueStr(request, "password_again");

		int res = baseService.changPassword(account, password, password_again);
		switch (res) {
		case 0:
			return renderFail(model, "该用户不存在");
		case -1:
			return renderFail(model, "账号不可为空");
		case -2:
			return renderFail(model, "新密码/确认密码不可为空");
		case -3:
			return renderFail(model, "新密码与确认密码不一致");
		default:
			return renderSuccess(res, model);
		}
	}

	/**
	 * 角色列表
	 * @param model
	 * @param account
	 * @return
	 */
	@RequiresRoles("manage")
	@RequestMapping("role/list.json")
	public Model roleList(Model model, @RequestParam(name = "account", required = true, defaultValue = "") String account) {
		return renderList(baseService.selectUserRole(account), model);
	}

	/**
	 * 保存角色
	 * @param json
	 * @param model
	 * @return
	 */
	@RequiresRoles("manage")
	@RequestMapping("role/save.json")
	public Model roleSave(@RequestBody JSONObject json, Model model) {
		if (json == null) return renderFail(model, "参数为空");
		return renderSuccess(baseService.insertRoleResource(json.getString("account"), json.getJSONArray("ids")), model);
	}
}
